package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLLoaderDataFormat;
	import flash.utils.ByteArray;
	import nochump.util.zip.ZipEntry;
	import nochump.util.zip.ZipFile;
	
	/**
	 * ...
	 * @author db0@qq.com
	 */
	public class DocxParser extends Sprite
	{
		private var bytes:ByteArray = null;
		private var zipFile:ZipFile = null;
		private var xml:XML = null;
		private var paragraphs:Array = null;
		
		public function DocxParser(bytes:ByteArray = null)
		{
			super();
			if (bytes)
			{
				this.bytes = bytes;
				unzip();
			}
			else
			{
				SwfLoader.loadData("gv.docx", loaded, URLLoaderDataFormat.BINARY);
			}
		}
		
		private function loaded(e:Event):void
		{
			if (e && e.type == Event.COMPLETE)
			{
				bytes = e.target.data as ByteArray;
			}
			unzip();
		}
		
		private function unzip():void
		{
			if (bytes == null)
				return;
			if (zipFile == null)
			{
				zipFile = new ZipFile(bytes);
				trace(zipFile.entries.join("\n"));
				trace("===========================");
			}
			var entry:ZipEntry = zipFile.getEntry("word/document.xml");
			if (entry)
			{
				var data:ByteArray = zipFile.getInput(entry);
				if (data)
				{
					xml = XML(data);
					var ns:Namespace = xml.namespace("w");
					
					var i:int = 0;
					for each (var p:XML in xml.ns::body.ns::p)
					{
						if (paragraphs == null)
							paragraphs = new Array();
						paragraphs[i] = "";
						for each (var node:XML in p.ns::r)
						{
							paragraphs[i] += node.ns::t;
						}
						++i;
					}
					trace(paragraphs);
				}
			}
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			if (paragraphs)
				addChild(new MyText(3, 10, stage.stageWidth - 6, stage.stageHeight-10, String(paragraphs.join("\n"))));
		}
	}
}